/**
 * Copyright (c) 2014 CoderKiss
 * CoderKiss[AT]gmail.com
 */

package com.zx.kitchen.index.common.utils;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.text.format.Time;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Random;

@SuppressLint("SimpleDateFormat")
public class TimeUtil {

    public static final String TAG = "TimeUtil";

    public static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String UTC_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
    public static final String FILE_FORMAT = "yyyy_MM_dd_HH_mm_ss_SSS";
    public static final String Full_Time = "yyyy-MM-dd HH:mm";
    public static final String year_and_month = "yyyy年MM月";
    public static final String year_and_month_and_day = "yyyy-MM-dd";
    public static final String yearMonthDay = "yyyy年MM月dd日";

    public static final String DATE_TIME_LASTMODIFIED = "yyyy-MM-dd HH:mm";
    public static final String DATE_TIME_LASTMODIFIED_NOYEAR = "MM-dd HH:mm";
    protected static final String DATE_TIME_TODAY = "今天 HH:mm";// 今天
    protected static final String DATE_TIME_YESTERDAY = "昨天 HH:mm";// 昨天
    protected static final String DATE_TIME_NOT_TODAY_FORMAT = "MM-dd";// 非今天
    protected static final String DATA_TIME = "HH:mm";
    private final static ThreadLocal<SimpleDateFormat> timeFormat = new ThreadLocal<SimpleDateFormat>() {

        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };
    public static long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
    public static long nh = 1000 * 60 * 60;// 一小时的毫秒数
    public static long nm = 1000 * 60;// 一分钟的毫秒数
    public static long ns = 1000;// 一秒钟的毫秒数

    public static long format(String time, String format) {
        if (TextUtils.isEmpty(time)) {
            return 0;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        long modified = 0;
        try {
            Date date = sdf.parse(time);
            modified = date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return modified;
    }

    public static String format(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_FORMAT);
        Date date = new Date(time);
        return sdf.format(date);
    }

    //将得到的时间戳转换成任意想得到的时间格式
    public static String format(long time, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = new Date(time);
        return sdf.format(date);
    }

    public static String format(Date date, String format) {
        if (TextUtils.isEmpty(format) || date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    public static String format(String timeStr, String srcFormat, String dstFormat) {
        long time = format(timeStr, srcFormat);
        String result = format(time, dstFormat);
        return result;
    }

    public static String utcToLocal(String utcTime) {
        String localTime = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(UTC_FORMAT);
            Date date = sdf.parse(utcTime);
            sdf.applyPattern(DEFAULT_FORMAT);
            localTime = sdf.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return localTime;
    }

    public static String getToday() {
        Date dateNow = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateNowStr = dateFormat.format(dateNow);
        return dateNowStr;
    }

    public static String getFullTime() {
        return format(new Date(), Full_Time);
    }

    public static String getFullTime(long timeStamp) {
        return format(new Date(timeStamp), Full_Time);
    }

    public static Calendar getStrTime(long cc_time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(cc_time);
        return calendar;
    }

    /**
     * Method name: getFormatTime <BR>
     * Description: 得到格式化好的时间显示 <BR>
     * Remark: <BR>
     *
     * @param millis  毫秒数
     * @param pattern format的格式 例：YYYY-MM-DD
     * @return String<BR>
     */
    public static String getFormatTime(long millis, String pattern) {
        String resultStr = null;
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
            resultStr = dateFormat.format(millis);
        } catch (NullPointerException e) {
            e.printStackTrace();
            resultStr = "";
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            resultStr = "";
        }
        return resultStr;
    }

    public static String getFormatTime(String millisStr, String pattern) {
        String resultStr = null;
        long millis = 0L;
        try {
            millis = Long.parseLong(millisStr);
        } catch (NumberFormatException e) {
            millis = 0L;
        }
        resultStr = getFormatTime(millis, pattern);
        return resultStr;
    }

    public static String getStrTime_yyyy_mm_dd(String cc_time) {
        try {
            String re_StrTime = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long lcc_time = Long.valueOf(cc_time);
            re_StrTime = sdf.format(new Date(lcc_time));
            return re_StrTime;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * Method name: getTime <BR>
     * Description: 将字符串转为时间戳 <BR>
     * Remark: <BR>
     *
     * @param user_time
     * @return String<BR>
     */
    public static String getTime(String user_time) {
        String re_time = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date d;
        try {
            d = sdf.parse(user_time);
            long l = d.getTime();
            re_time = String.valueOf(l);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return re_time;
    }

    public static String getStrTime_yyyy(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time));
        return re_StrTime;
    }

    public static String getStrTime(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time));
        return re_StrTime;
    }

    public static String getStrTimeMonthDay(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time));
        return re_StrTime;
    }

    public static String getStrTime_mm_dd(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm");
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date((lcc_time)));
        if (re_StrTime.contains(getNewData())) {
            SimpleDateFormat sdf_mmdd = new SimpleDateFormat("HH:mm");
            long mmdd_time = Long.valueOf(cc_time);
            String mmdd_str = sdf_mmdd.format(new Date((mmdd_time)));
            re_StrTime = "今日" + mmdd_str;
        }
        return re_StrTime;
    }

    public static String getNewData() {
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String str = sdf.format(curDate);
        return str;
    }

    /**
     * 获取现在时间
     */
    public static Date getNowDateShort() {

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        ParsePosition pos = new ParsePosition(8);
        Date currentTime_2 = formatter.parse(dateString, pos);
        return currentTime_2;
    }

    // 将毫秒数换算成x天x时x分x秒x毫秒
    public static String dataDiff(long ms) {
        int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;

        long day = ms / dd;
        long hour = (ms - day * dd) / hh;
        long minute = (ms - day * dd - hour * hh) / mi;

        // long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        // long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
        //
        // // String strDay = day < 10 ? "0" + day : "" + day;
        // // String strHour = hour < 10 ? "0" + hour : "" + hour;
        // // String strMinute = minute < 10 ? "0" + minute : "" + minute;
        // // String strSecond = second < 10 ? "0" + second : "" + second;
        // // String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;
        // // strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : "" + strMilliSecond;
        // // return strDay + ":" + strHour + ":" + strMinute + ":" + strSecond + ":" + strMilliSecond;

        String dayStr = day < 1 ? "" : day + "天";
        String hourStr = hour < 1 ? "0小时" : hour + "小时";
        String minStr = minute < 1 ? "0分钟" : minute + "分钟";

        return dayStr + hourStr + minStr;
    }

    //
    public static String parseDate(String createTime) {
        String ret = "";
        try {
            long create = Long.valueOf(createTime);
            Calendar now = Calendar.getInstance();
            long ms = 1000 * (now.get(Calendar.HOUR_OF_DAY) * 3600 + now.get(Calendar.MINUTE) * 60 + now.get(Calendar.SECOND));// 毫秒数
            long ms_now = System.currentTimeMillis();
            if (ms_now - create < ms) {
                ret = "今天";
            } else if (ms_now - create < (ms + 24 * 3600 * 1000)) {
                ret = "昨天";
            } else if (ms_now - create < (ms + 24 * 3600 * 1000 * 2)) {
                ret = "前天";
            } else {
                ret = "更早";
            }
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    // 两个毫秒时间相差的天，小时。。。。。
    public static String dataDiff(long startTime, long endTime) {
        String str = "";
        long diff = 0;
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        // 获得两个时间的毫秒时间差异
        diff = endTime - startTime;
        long day = diff / nd;// 计算差多少天
        long hour = diff % nd / nh;// 计算差多少小时
        long min = diff % nd % nh / nm;// 计算差多少分钟
        long sec = diff % nd % nh % nm / ns;// 计算差多少秒

        String dayStr = day < 1 ? "" : day + "天";
        String hourStr = hour < 1 ? "0小时" : hour + "小时";
        String minStr = min < 1 ? "0分钟" : min + "分钟";

        str = dayStr + hourStr + minStr;

        return str;

    }

    // 将毫秒转化为分秒
    public static String formatLongToHHMM2(long timelong) {
        String hms = "";
        String m = "";
        String s = "";

        long minutes = (timelong / (1000L * 60L));
        long seconds = (timelong - minutes * (1000L * 60L)) / 1000L;

        if (minutes <= 9 && minutes > 0) {
            m = "0" + minutes;
        } else if (minutes == 0) {
            m = "00";
        } else if (minutes >= 10) {
            m = minutes + "";
        }
        if (seconds <= 9 && seconds > 0) {
            s = "0" + seconds;
        } else if (seconds == 0) {
            s = "00";
        } else if (seconds >= 10) {
            s = seconds + "";
        }
        hms = m + ":" + s;
        return hms;
    }


    // 加分钟
    public static long dataDiff(long startTime, int min) {
        long diff = 0;
        long nm = 1000 * 60;// 一分钟的毫秒数
        diff = startTime + (nm * min);
        return diff;

    }

    // 将毫秒转化为小时和分钟
    public static String formatlong(long diff) {
        String str = "";
        // long diff = 0;
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long day = diff / nd;// 计算差多少天
        long hour = diff % nd / nh;// 计算差多少小时
        long min = diff % nd % nh / nm;// 计算差多少分钟
        long sec = diff % nd % nh % nm / ns;// 计算差多少秒
        // str = day + "," + hour + "," + min + "," + sec;
        str = "剩余" + hour + "小时" + min + "分钟失效";
        return str;

    }

    // 将毫秒转化为分秒
    public static String formatLongToHHMM(long timelong) {
        String hms = "";
        String m = "";
        String s = "";

        long minutes = (timelong / (1000L * 60L));
        long seconds = (timelong - minutes * (1000L * 60L)) / 1000L;

        if (minutes <= 9 && minutes > 0) {
            m = "0" + minutes;
        } else if (minutes == 0) {
            m = "00";
        } else if (minutes >= 10) {
            m = minutes + "";
        }
        if (seconds <= 9 && seconds > 0) {
            s = "0" + seconds;
        } else if (seconds == 0) {
            s = "00";
        } else if (seconds >= 10) {
            s = seconds + "";
        }
        hms = m + ":" + s;
        return hms;
    }

    public static void getCurrentDateTime() {
        Time time = new Time("GMT+8");
        time.setToNow();
        int year = time.year;
        int month = time.month;
        int day = time.monthDay;
        int minute = time.minute;
        int hour = time.hour;
        int sec = time.second;
        String timde = "当前时间为：" + year + "年 " + month + "月 " + day + "日 " + hour + "时 " + minute + "分 " + sec + "秒";
    }

    public static String getLastModifiedFomat(String unixtime, String dateFormat) {
        String tmpdatestr = "";
        try {
            long unixtimeInt = Long.parseLong(unixtime);
            if (unixtimeInt != 0) {
                SimpleDateFormat tmpfmt = new SimpleDateFormat(dateFormat);
                tmpdatestr = tmpfmt.format(new Date(unixtimeInt));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return tmpdatestr;
    }

    public static String diffTimeTool(long unixtimeInt) {

        long difftime = System.currentTimeMillis() - unixtimeInt;

        if (difftime < 60 * 1000) {
            return "刚刚";
        } else {
            long minute = difftime / (60 * 1000);
            minute = (int) minute;
            if (minute > 30) {
                Timestamp tmpdate = new Timestamp(unixtimeInt);
                // 判断年月日
                final Calendar c = Calendar.getInstance();
                int year = c.get(Calendar.YEAR) - 1900;
                int month = c.get(Calendar.MONTH);
                int day = c.get(Calendar.DATE);
                String formatString = DATE_TIME_LASTMODIFIED;
                if (year == tmpdate.getYear() && month == tmpdate.getMonth() && day == tmpdate.getDate()) {
                    formatString = DATE_TIME_TODAY;
                } else if (year == tmpdate.getYear() && month == tmpdate.getMonth() && day == (tmpdate.getDate() + 1)) {
                    formatString = DATE_TIME_YESTERDAY;
                }
                SimpleDateFormat tmpfmt = new SimpleDateFormat(formatString);
                return tmpfmt.format(tmpdate);
            } else {
                return minute + "分钟前";
            }
        }
    }

    public static String diffTimeToolNoYear(long difftime, String time, Date nowtime) {

        if (difftime < 60 * 1000) {
            return "刚刚";
        } else {
            long minute = difftime / (60 * 1000);
            minute = (int) minute;
            if (minute > 30) {
                Timestamp tmpdate = new Timestamp(Long.parseLong(time));
                // 判断年月日
                final Calendar c = Calendar.getInstance();
                int year = c.get(Calendar.YEAR) - 1900;
                int month = c.get(Calendar.MONTH);
                int day = c.get(Calendar.DATE);
                String formatString = DATE_TIME_LASTMODIFIED_NOYEAR;
                if (year == tmpdate.getYear() && month == tmpdate.getMonth() && day == tmpdate.getDate()) {
                    formatString = DATE_TIME_TODAY;
                } else if (year == tmpdate.getYear() && month == tmpdate.getMonth() && day == (tmpdate.getDate() + 1)) {
                    formatString = DATE_TIME_YESTERDAY;
                }
                SimpleDateFormat tmpfmt = new SimpleDateFormat(formatString);
                return tmpfmt.format(tmpdate);
            } else {
                return minute + "分钟前";
            }
        }
    }

    /**
     * nixtime转化成yyyy-MM-dd HH:mm
     *
     * @param unixtime
     * @return
     */
    public static String getFormatDateTimeFromUnixTime(String unixtime, String formatString) {
        if (formatString == null) {
            formatString = DATE_TIME_NOT_TODAY_FORMAT;
        }
        String tmpdatestr = "";
        try {
            long unixtimeInt = Long.parseLong(unixtime);
            if (unixtimeInt != 0) {
                Timestamp tmpdate = new Timestamp(unixtimeInt * 1000L);
                // 判断年月日
                final Calendar c = Calendar.getInstance();
                int year = c.get(Calendar.YEAR) - 1900;
                int month = c.get(Calendar.MONTH);
                int day = c.get(Calendar.DATE);

                if (year == tmpdate.getYear() && month == tmpdate.getMonth() && day == tmpdate.getDate()) {
                    formatString = DATE_TIME_TODAY;
                } else if (year == tmpdate.getYear() && month == tmpdate.getMonth() && day == (tmpdate.getDate() + 1)) {
                    formatString = DATE_TIME_YESTERDAY;
                }
                SimpleDateFormat tmpfmt = new SimpleDateFormat(formatString);
                tmpdatestr = tmpfmt.format(tmpdate);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return tmpdatestr;
    }

    /**
     * nixtime转化成yyyy-MM-dd HH:mm
     *
     * @param unixtime
     * @return
     */
    public static String getLastModifiedFomat(String unixtime) {
        String tmpdatestr = "";
        try {
            long unixtimeInt = Long.parseLong(unixtime);
            if (unixtimeInt != 0) {
                Timestamp tmpdate = new Timestamp(unixtimeInt);
                SimpleDateFormat tmpfmt = new SimpleDateFormat(DATE_TIME_LASTMODIFIED);
                tmpdatestr = tmpfmt.format(tmpdate);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return tmpdatestr;
    }

    public static String getLastModifiedFomatNoY(String unixtime) {
        String tmpdatestr = "";
        try {
            long unixtimeInt = Long.parseLong(unixtime);
            if (unixtimeInt != 0) {
                Timestamp tmpdate = new Timestamp(unixtimeInt);
                SimpleDateFormat tmpfmt = new SimpleDateFormat(DATE_TIME_LASTMODIFIED_NOYEAR);
                tmpdatestr = tmpfmt.format(tmpdate);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return tmpdatestr;
    }

    // 只显示时间不显示日期
    public static String getLastModifiedFomatData(String unixtime) {
        String tmpdatestr = "";
        try {
            long unixtimeInt = Long.parseLong(unixtime);
            if (unixtimeInt != 0) {
                Timestamp tmpdate = new Timestamp(unixtimeInt);
                SimpleDateFormat tmpfmt = new SimpleDateFormat(DATA_TIME);
                tmpdatestr = tmpfmt.format(tmpdate);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return tmpdatestr;
    }

    /**
     * nixtime转化成yyyy-MM-dd HH:mm
     *
     * @param unixtime
     * @return
     */
    public static String getLastModifiedFomatForChina(String unixtime) {
        String tmpdatestr = "";
        try {
            long unixtimeInt = Long.parseLong(unixtime);
            if (unixtimeInt != 0) {
                Timestamp tmpdate = new Timestamp(unixtimeInt);
                SimpleDateFormat tmpfmt = new SimpleDateFormat("MM月dd日 E ahh:mm");
                tmpdatestr = tmpfmt.format(tmpdate);
                tmpdatestr = tmpdatestr.replace("星期", "周").replace("AM", "上午").replace("PM", "下午");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return tmpdatestr;
    }

    public static String dayForWeek(SimpleDateFormat format, String pTime) throws Exception {
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(pTime));
        int dayForWeek = 0;
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            dayForWeek = 7;
        } else {
            dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        String dayForWeekStr = "";
        switch (dayForWeek) {
            case 1:
                dayForWeekStr = "星期一";
                break;
            case 2:
                dayForWeekStr = "星期二";
                break;
            case 3:
                dayForWeekStr = "星期三";
                break;
            case 4:
                dayForWeekStr = "星期四";
                break;
            case 5:
                dayForWeekStr = "星期五";
                break;
            case 6:
                dayForWeekStr = "星期六";
                break;
            case 7:
                dayForWeekStr = "星期日";
                break;
            default:
                break;
        }
        return dayForWeekStr;
    }

    public static Date strToTime(String str) {
        Date date = null;
        try {
            date = timeFormat.get().parse(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

    // public static String getfriendlyFormat(String stratTime) {
    //
    // Date date = null;
    // try {
    // date = new Date(Long.valueOf(stratTime));
    // } catch (Exception e) {
    // date = new Date();
    // }
    //
    // Date date2 = new Date();
    // return twoDateDistance(date, date2);
    //
    // }

    /**
     * 返回距离当前时间天数 Method name: betweenDay <BR>
     * Description: betweenDay <BR>
     *
     * @param stratTime
     * @return Long<BR>
     */
    public static Long betweenDay(String stratTime) {
        Date startDate = null;
        try {
            startDate = new Date(Long.valueOf(stratTime));
        } catch (Exception e) {
            startDate = new Date();
        }
        Date endDate = new Date();
        Long timeLong = endDate.getTime() - startDate.getTime();
        timeLong = timeLong / 1000 / 60 / 60 / 24;
        return timeLong;
    }


    public static String getfriendlyFormat(String stratTime) {
        Date date = null;
        try {
            date = new Date(Long.valueOf(stratTime));
        } catch (Exception e) {
            date = new Date();
        }
        return twoDateDistances(date);
    }

    public static String twoDateDistances(Date startDate) {
        if (startDate == null) {
            return "刚刚";
        }
        Calendar ecalendar = Calendar.getInstance();
        ecalendar.setTime(new Date());
        Calendar scalendar = Calendar.getInstance();
        scalendar.setTime(startDate);

        long timeLong = ecalendar.getTime().getTime() - scalendar.getTime().getTime();

        if (timeLong < 60 * 1000 * 2) {
            return "刚刚";
        } else if (timeLong < 60 * 60 * 1000) {
            timeLong = timeLong / 1000 / 60;
            return timeLong + "分钟前";
        } else if (timeLong < 60 * 60 * 24 * 1000) {
            timeLong = timeLong / 60 / 60 / 1000;
            return timeLong + "小时前";
        } else if (timeLong < 60 * 60 * 24 * 1000 * 2) {
            return "昨天";
        } else if (timeLong < 60 * 60 * 24 * 1000 * 3) {
            return "前天";
        } else if (ecalendar.get(Calendar.YEAR) > scalendar.get(Calendar.YEAR)) {
            return format(startDate, "yyyy年MM月dd日");
        } else {
            return format(startDate, "MM月dd日");
        }
    }

    public static Date addMonth(String sdate, int month) {
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(new Date(Long.valueOf(sdate)));
        } catch (Exception e) {
            calendar.setTime(new Date());
        }

        calendar.add(Calendar.MONTH, month);
        return calendar.getTime();
    }

    public static Date addDay(String sdate, int day) {
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(new Date(Long.valueOf(sdate)));
        } catch (Exception e) {
            calendar.setTime(new Date());
        }

        calendar.add(Calendar.DAY_OF_WEEK, day);
        return calendar.getTime();
    }


    //// TODO: 2016/4/20


    /**
     * 获取现在时间
     *
     * @return 返回时间类型 yyyy-MM-dd HH:mm:ss
     */
    public static Date getNowDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        ParsePosition pos = new ParsePosition(8);
        Date currentTime_2 = formatter.parse(dateString, pos);
        return currentTime_2;
    }

    /**
     * 获取现在时间
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 获取现在时间
     *
     * @return 返回短时间字符串格式yyyy-MM-dd
     */
    public static String getStringDateShort() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 获取时间 小时:分;秒 HH:mm:ss
     *
     * @return
     */
    public static String getTimeShort() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        Date currentTime = new Date();
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
     *
     * @param strDate
     * @return
     */
    public static Date strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /**
     * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
     *
     * @param dateDate
     * @return
     */
    public static String dateToStrLong(Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(dateDate);
        return dateString;
    }

    /**
     * 将短时间格式时间转换为字符串 yyyy-MM-dd
     *
     * @param dateDate
     * @return
     */
    public static String dateToStr(Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(dateDate);
        return dateString;
    }

    /**
     * 将短时间格式字符串转换为时间 yyyy-MM-dd
     *
     * @param strDate
     * @return
     */
    public static Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /**
     * 得到现在时间
     *
     * @return
     */
    public static Date getNow() {
        Date currentTime = new Date();
        return currentTime;
    }

    /**
     * 提取一个月中的最后一天
     *
     * @param day
     * @return
     */
    public static Date getLastDate(long day) {
        Date date = new Date();
        long date_3_hm = date.getTime() - 3600000 * 34 * day;
        Date date_3_hm_date = new Date(date_3_hm);
        return date_3_hm_date;
    }

    /**
     * 得到现在时间
     *
     * @return 字符串 yyyyMMdd HHmmss
     */
    public static String getStringToday() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 得到现在小时
     */
    public static String getHour() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        String hour;
        hour = dateString.substring(11, 13);
        return hour;
    }

    /**
     * 得到现在分钟
     *
     * @return
     */
    public static String getTime() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        String min;
        min = dateString.substring(14, 16);
        return min;
    }

    /**
     * 根据用户传入的时间表示格式，返回当前时间的格式 如果是yyyyMMdd，注意字母y不能大写。
     *
     * @param sformat yyyyMMddhhmmss
     * @return
     */
    public static String getUserDate(String sformat) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(sformat);
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 二个小时时间间的差值,必须保证二个时间都是"HH:MM"的格式，返回字符型的分钟
     */
    public static String getTwoHour(String st1, String st2) {
        String[] kk = null;
        String[] jj = null;
        kk = st1.split(":");
        jj = st2.split(":");
        if (Integer.parseInt(kk[0]) < Integer.parseInt(jj[0]))
            return "0";
        else {
            double y = Double.parseDouble(kk[0]) + Double.parseDouble(kk[1]) / 60;
            double u = Double.parseDouble(jj[0]) + Double.parseDouble(jj[1]) / 60;
            if ((y - u) > 0)
                return y - u + "";
            else
                return "0";
        }
    }

    /**
     * 得到二个日期间的间隔天数
     */
    public static String getTwoDay(String sj1, String sj2) {
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        long day = 0;
        try {
            Date date = myFormatter.parse(sj1);
            Date mydate = myFormatter.parse(sj2);
            day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
        } catch (Exception e) {
            return "";
        }
        return day + "";
    }

    /**
     * 时间前推或后推分钟,其中JJ表示分钟.
     */
    public static String getPreTime(String sj1, String jj) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String mydate1 = "";
        try {
            Date date1 = format.parse(sj1);
            long Time = (date1.getTime() / 1000) + Integer.parseInt(jj) * 60;
            date1.setTime(Time * 1000);
            mydate1 = format.format(date1);
        } catch (Exception e) {
        }
        return mydate1;
    }

    /**
     * 得到一个时间延后或前移几天的时间,nowdate为时间,delay为前移或后延的天数
     */
    public static String getNextDay(String nowdate, String delay) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String mdate = "";
            Date d = strToDate(nowdate);
            long myTime = (d.getTime() / 1000) + Integer.parseInt(delay) * 24 * 60 * 60;
            d.setTime(myTime * 1000);
            mdate = format.format(d);
            return mdate;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 判断是否润年
     *
     * @param ddate
     * @return
     */
    public static boolean isLeapYear(String ddate) {

        /**
         * 详细设计： 1.被400整除是闰年，否则： 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年
         * 3.能被4整除同时能被100整除则不是闰年
         */
        Date d = strToDate(ddate);
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        gc.setTime(d);
        int year = gc.get(Calendar.YEAR);
        if ((year % 400) == 0)
            return true;
        else if ((year % 4) == 0) {
            if ((year % 100) == 0)
                return false;
            else
                return true;
        } else
            return false;
    }

    /**
     * 返回美国时间格式 26 Apr 2006
     *
     * @param str
     * @return
     */
    public static String getEDate(String str) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(str, pos);
        String j = strtodate.toString();
        String[] k = j.split(" ");
        return k[2] + k[1].toUpperCase() + k[5].substring(2, 4);
    }

    /**
     * 获取一个月的最后一天
     *
     * @param dat
     * @return
     */
    public static String getEndDateOfMonth(String dat) {// yyyy-MM-dd
        String str = dat.substring(0, 8);
        String month = dat.substring(5, 7);
        int mon = Integer.parseInt(month);
        if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12) {
            str += "31";
        } else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
            str += "30";
        } else {
            if (isLeapYear(dat)) {
                str += "29";
            } else {
                str += "28";
            }
        }
        return str;
    }

    /**
     * 判断二个时间是否在同一个周
     *
     * @param date1
     * @param date2
     * @return
     */
    public static boolean isSameWeekDates(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date1);
        cal2.setTime(date2);
        int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
        if (0 == subYear) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        } else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
            // 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        } else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        }
        return false;
    }

    /**
     * 产生周序列,即得到当前时间所在的年度是第几周
     *
     * @return
     */
    public static String getSeqWeek() {
        Calendar c = Calendar.getInstance(Locale.CHINA);
        String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));
        if (week.length() == 1)
            week = "0" + week;
        String year = Integer.toString(c.get(Calendar.YEAR));
        return year + week;
    }

    /**
     * 获得一个日期所在的周的星期几的日期，如要找出2002年2月3日所在周的星期一是几号
     *
     * @param sdate
     * @param num
     * @return
     */
    public static String getWeek(String sdate, String num) {
        // 再转换为时间
        Date dd = strToDate(sdate);
        Calendar c = Calendar.getInstance();
        c.setTime(dd);
        if (num.equals("1")) // 返回星期一所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        else if (num.equals("2")) // 返回星期二所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
        else if (num.equals("3")) // 返回星期三所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
        else if (num.equals("4")) // 返回星期四所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
        else if (num.equals("5")) // 返回星期五所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        else if (num.equals("6")) // 返回星期六所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
        else if (num.equals("0")) // 返回星期日所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
    }

    /**
     * 根据一个日期，返回是星期几的字符串
     *
     * @param sdate
     * @return
     */
    public static String getWeek(String sdate) {
        // 再转换为时间
        Date date = strToDate(sdate);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        // int hour=c.get(Calendar.DAY_OF_WEEK);
        // hour中存的就是星期几了，其范围 1~7
        // 1=星期日 7=星期六，其他类推
        return new SimpleDateFormat("EEEE").format(c.getTime());
    }

    /**
     * 两个时间之间的天数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static long getDays(String date1, String date2) {
        if (date1 == null || date1.equals(""))
            return 0;
        if (date2 == null || date2.equals(""))
            return 0;
        // 转换为标准时间
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        Date mydate = null;
        try {
            date = myFormatter.parse(date1);
            mydate = myFormatter.parse(date2);
        } catch (Exception e) {
        }
        long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
        return day;
    }

    /**
     * 二个小时时间间的差值,必须保证二个时间都是"HH:MM"的格式，返回字符型的分钟
     */
    public static int getTwoMinutes(String st1, String st2) {
        String[] kk = null;
        String[] jj = null;
        kk = st1.split(":");
        jj = st2.split(":");
        int int1 = Integer.parseInt(kk[0]) * 60 + Integer.parseInt(kk[1]);
        int int2 = Integer.parseInt(jj[0]) * 60 + Integer.parseInt(jj[1]);
        if (int1 < int2)
            return 0;
        else {
            if ((int1 - int2) > 0)
                return (int1 - int2);
            else
                return 0;
        }
    }

    /**
     * 形成如下的日历 ， 根据传入的一个时间返回一个结构 星期日 星期一 星期二 星期三 星期四 星期五 星期六 下面是当月的各个时间
     * 此函数返回该日历第一行星期日所在的日期
     *
     * @param sdate
     * @return
     */

    public static String getNowMonth(String sdate) {
        // 取该时间所在月的一号
        sdate = sdate.substring(0, 8) + "01";

        // 得到这个月的1号是星期几
        Date date = strToDate(sdate);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int u = c.get(Calendar.DAY_OF_WEEK);
        String newday = getNextDay(sdate, (1 - u) + "");
        return newday;
    }

    /**
     * 取得数据库主键 生成格式为yyyymmddhhmmss+k位随机数
     *
     * @param k 表示是取几位随机数，可以自己定
     */

    public static String getNo(int k) {

        return getUserDate("yyyyMMddhhmmss") + getRandom(k);
    }

    /**
     * 返回一个随机数
     *
     * @param i
     * @return
     */
    public static String getRandom(int i) {
        Random jjj = new Random();
        // int suiJiShu = jjj.nextInt(9);
        if (i == 0)
            return "";
        String jj = "";
        for (int k = 0; k < i; k++) {
            jj = jj + jjj.nextInt(9);
        }
        return jj;
    }

    /**
     */
    public static boolean RightDate(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        ;
        if (date == null)
            return false;
        if (date.length() > 10) {
            sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        } else {
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        }
        try {
            sdf.parse(date);
        } catch (ParseException pe) {
            return false;
        }
        return true;
    }


}
